﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;

using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Windows.Data;

using ProjManagSolution.pmMyWebService;
using ProjManagSolution.anMyWebService;
using System.Windows.Browser;

/* REMEMBER TO GET PHASE LIST */

namespace ProjManagSolution
{
    public partial class InvolvedProject : Page
    {
        protected List<milestone> msl = new List<milestone>(); //list of milestones
        protected List<phase> pl = new List<phase>(); //list of phases
        protected List<user> ml = new List<user>(); //list of members
        protected List<milestone> milestoneList = new List<milestone>();//milestone list
        protected List<string> roleList = new List<string>(); // list of role for member
        protected List<task> taskList = new List<task>(); // list of task
        protected List<documentation> documentList = new List<documentation>(); // documentation list
        
        protected user currentUserForUploadPurpose;
        string userEmail;


        protected project currProject = new project();
        int projectID;
        protected user curUser = new user();
        protected string curUserRole;

        public InvolvedProject(int pid = 0)
        {
            Session s = new Session();
            userEmail = s.GetUserEmail();
            InitializeComponent();

            //set the project id
            projectID = pid;

            //get project info
            GetProjectInfo();

            //get user information
            GetUserInfo();

            ////get the current user information
            GetCurrentUserInfo();

            //get member list of project
            GetMemberList();

            //get milestone
            GetMilestone();

            //get reports
            GetDocumentations();

            
            //get task list
            GetProjectTaskList();            
        }

        //GET USER INFO
        protected void GetUserInfo()
        {
            pmWebServiceClient ws = new pmWebServiceClient();
            Session s = new Session();
            string userEmail = s.GetUserEmail();
            ws.GetUserDetailByEmailCompleted += new EventHandler<GetUserDetailByEmailCompletedEventArgs>(ws_GetUserDetailByEmailCompleted);
            ws.GetUserDetailByEmailAsync(userEmail);
        }

        protected void GetCurrentUserInfo()
        {
            pmWebServiceClient ws = new pmWebServiceClient();
            ws.GetUserDetailByEmailCompleted += new EventHandler<GetUserDetailByEmailCompletedEventArgs>(ws_GetUserDetailByEmailCompleted);
            ws.GetUserDetailByEmailAsync(userEmail);
        }

        void ws_GetUserDetailByEmailCompleted(object sender, GetUserDetailByEmailCompletedEventArgs e)
        {
            curUser = e.Result;
            this.txtblokEmail.Text = curUser.user_email;

            currentUserForUploadPurpose = e.Result;

            //get the user role
            pmWebServiceClient ws = new pmWebServiceClient();

            ws.GetRoleByUserCompleted += new EventHandler<GetRoleByUserCompletedEventArgs>(ws_GetRoleByUserCompleted);
            ws.GetRoleByUserAsync(curUser.user_id, projectID);
        }

        void ws_GetRoleByUserCompleted(object sender, GetRoleByUserCompletedEventArgs e)
        {
            curUserRole = e.Result;

            //show/hide tab for specific user role
            if (curUserRole == "Team Lead")
            {
                Initialize_TeamLead();
            }
            else if (curUserRole == "Team Member")
            {
                Initialize_TeamMember();
            }
            else
            {
                Initialize_Observer();
            }
        }

        //INITIALIZE USER ROLE: TEAM LEAD
        void Initialize_TeamLead()
        {
            this.tabItemTeamLeadTask.Visibility = System.Windows.Visibility.Visible;
            this.tabItemTeamLeadReport.Visibility = System.Windows.Visibility.Visible;
            this.tabItemTeamMemberReport.Visibility = System.Windows.Visibility.Collapsed;
            this.tabItemTeamMemberTask.Visibility = System.Windows.Visibility.Collapsed;
        }

        //INITIALIZE USER ROLE: TEAM MEMBER
        void Initialize_TeamMember()
        {
            this.tabItemTeamMemberTask.Visibility = System.Windows.Visibility.Visible;
            this.tabItemTeamMemberReport.Visibility = System.Windows.Visibility.Visible;
            this.tabItemTeamLeadReport.Visibility = System.Windows.Visibility.Collapsed;
            this.tabItemTeamLeadTask.Visibility = System.Windows.Visibility.Collapsed;
        }

        //INITIALIZE USER ROLE: OBSERVER
        void Initialize_Observer()
        {
            this.tabItemTeamMemberTask.Visibility = System.Windows.Visibility.Collapsed;
            this.tabItemTeamMemberReport.Visibility = System.Windows.Visibility.Visible;
            this.tabItemTeamLeadReport.Visibility = System.Windows.Visibility.Collapsed;
            this.tabItemTeamLeadTask.Visibility = System.Windows.Visibility.Collapsed;
        }

        //GET PROJECT INFO
        protected void GetProjectInfo()
        {
            pmWebServiceClient ws = new pmWebServiceClient();
            ws.GetProjectDetailCompleted += new EventHandler<GetProjectDetailCompletedEventArgs>(ws_GetProjectDetailCompleted);
            ws.GetProjectDetailAsync(projectID);
        }

        void ws_GetProjectDetailCompleted(object sender, GetProjectDetailCompletedEventArgs e)
        {
            currProject = e.Result;
            this.txtblokProjectName.Text = currProject.project_name.ToString();
            
            //Bind data to info page
            txtblokInfoPageProjectName.Text = currProject.project_name;
            txtblokStartDate.Text = currProject.project_start_date.ToString();
            txtblokInfoPageDesc.Text = currProject.project_description.ToString();
        }

        //GET PROJECT TEAM MEMBER
        protected void GetMemberList()
        {
            pmWebServiceClient ws = new pmWebServiceClient();
            ws.GetProjectMembersCompleted += new EventHandler<GetProjectMembersCompletedEventArgs>(ws_GetProjectMembersCompleted);
            ws.GetProjectMembersAsync(projectID);
        }

        protected void GetMilestone()
        {
            pmWebServiceClient ws = new pmWebServiceClient();
            ws.GetMilestonesCompleted += new EventHandler<GetMilestonesCompletedEventArgs>(ws_GetMilestonesCompleted);
            ws.GetMilestonesAsync(projectID);
        }

        protected void GetDocumentations()
        {
            pmWebServiceClient ws = new pmWebServiceClient();
            ws.GetFoldersCompleted += new EventHandler<GetFoldersCompletedEventArgs>(ws_GetFoldersCompleted);
            ws.GetFoldersAsync(projectID);
        }

        void ws_GetProjectMembersCompleted(object sender, GetProjectMembersCompletedEventArgs e)
        {
            ml = e.Result;
            List<Member> memberlist = new List<Member>();

            for (int i = 0; i < ml.Count; ++i)
            {
                memberlist.Add(new Member(ml[i].user_id.ToString(),
                    ml[i].user_email,
                    ml[i].user_firstname,
                    ml[i].user_lastname,
                    "Not Functional Yet",
                    Convert.ToDateTime(ml[i].user_birthday),
                    ml[i].user_sex.ToString(),
                    ml[i].user_address, ml[i].user_phone));
            }

            PagedCollectionView memberListView = new PagedCollectionView(memberlist);
            this.datagridMemberList.ItemsSource = memberListView;
            if (memberListView.CanGroup == true)
            {
                // Group tasks by Milestone Name
                memberListView.GroupDescriptions.Add(new PropertyGroupDescription("Role"));
            }
            if (memberListView.CanSort == true)
            {
                // By default, sort by Phase Name.
                memberListView.SortDescriptions.Add(new SortDescription("Email", ListSortDirection.Descending));
            }
        }


        //GET MILESTONE
        void ws_GetMilestonesCompleted(object sender, GetMilestonesCompletedEventArgs e)
        {
            //bind the milestone list to datagrid
            milestoneList = e.Result;
            List<Milestone> ML = new List<Milestone>();
            List<Phase> phaseList = new List<Phase>();

            for (int i = 0; i < milestoneList.Count; ++i)
            {
                ML.Add(new Milestone()
                {
                    ID = milestoneList[i].milestone_id.ToString(),
                    Name = milestoneList[i].milestone_name,
                    // Change here
                    StartDate = milestoneList[i].milestone_start_date,
                    EndDate = milestoneList[i].milestone_end_date,
                    Description = milestoneList[i].milestone_description
                });

                if (milestoneList[i].phases != null)
                {
                    for (int j = 0; j < milestoneList[i].phases.Count; ++j)
                    {
                        phaseList.Add(new Phase()
                        {
                            ID = milestoneList[i].phases[j].phase_id.ToString(),
                            Name = milestoneList[i].phases[j].phase_name,
                            MilestoneID = milestoneList[i].milestone_id.ToString(),
                            Milestone = milestoneList[i].milestone_name,
                            StartDate = milestoneList[i].phases[j].phase_start_date,
                            EndDate = milestoneList[i].phases[j].phase_end_date,
                            Description = milestoneList[i].phases[j].phase_description
                        });
                    }
                }
            }


            //bind Milestone
            this.datagridMilestone.ItemsSource = ML;

            // Implement datagrid
            PagedCollectionView phaseListView = new PagedCollectionView(phaseList);
            this.datagridPhase.ItemsSource = phaseListView;
            if (phaseListView.CanGroup == true)
            {
                // Group tasks by Milestone Name
                phaseListView.GroupDescriptions.Add(new PropertyGroupDescription("Milestone"));
            }
            if (phaseListView.CanSort == true)
            {
                // By default, sort by Phase Name.
                phaseListView.SortDescriptions.Add(new SortDescription("Phase Name", ListSortDirection.Descending));
            }

            //get phase

        }

        void ws_GetFoldersCompleted(object sender, GetFoldersCompletedEventArgs e)
        {
            documentList.Clear();
            List<folder> folderList = new List<folder>();
            List<Documentation> docList = new List<Documentation>();
            folderList = e.Result;

            foreach (folder eachFolder in folderList)
            {
                foreach (documentation eachDoc in eachFolder.documentations)
                {
                    documentList.Add(eachDoc);
                    docList.Add(new Documentation()
                    {
                        ID = eachDoc.documentation_id,
                        Name = eachDoc.documentation_name,
                        Status = eachDoc.documentation_status,
                        Url = eachDoc.documentation_url,
                        UploadDate = eachDoc.documentation_date
                    });
                }
            }

            this.datagridDocuments1.ItemsSource = docList;
            this.datagridDocuments2.ItemsSource = docList;
        }

        //ADD TASK-LIST DATA TO DATAGRID
        void AddData(List<task> in_task)
        {
            // Create a collection to store task data.
            ObservableCollection<Task> oTaskList = new ObservableCollection<Task>();
            ObservableCollection<MyTask> oMyTaskList = new ObservableCollection<MyTask>();

            // Remove this part to add actual data
            string[] priority = new string[3];
            priority[0] = "High";
            priority[1] = "Medium";
            priority[2] = "Low";

            bool status;
            for (int i = 0; i < in_task.Count; i++)
            {
                if (in_task[i].task_status == "Completed")
                    status = true;
                else
                    status = false;
                oTaskList.Add(new Task()
                {
                    PhaseName = in_task[i].phase.phase_name,
                    TaskName = in_task[i].task_name,
                    AssignedMember = in_task[i].assigns[0].user.user_email,
                    //Priority = priority[i % 3],
                    StartDate = in_task[i].task_start_date,
                    Deadline = in_task[i].task_end_date,
                    Complete = status,
                });
                oMyTaskList.Add(new MyTask()
                {
                    TaskID = in_task[i].task_id.ToString(),
                    PhaseName = in_task[i].phase.phase_name,
                    TaskName = in_task[i].task_name,
                    //Priority = priority[i % 3],
                    StartDate = in_task[i].task_start_date,
                    Deadline = in_task[i].task_end_date,
                    Complete = status,
                });
            }

            // Implement datagrid
            PagedCollectionView taskListView = new PagedCollectionView(oTaskList);
            this.datagridTaskList_TeamLead.ItemsSource = taskListView;
            if (taskListView.CanGroup == true)
            {
                // Group tasks by Phase Name
                taskListView.GroupDescriptions.Add(new PropertyGroupDescription("PhaseName"));
                // Then group by Complete status.
                taskListView.GroupDescriptions.Add(new PropertyGroupDescription("Complete"));
            }
            if (taskListView.CanSort == true)
            {
                // By default, sort by Task Name.
                taskListView.SortDescriptions.Add(new SortDescription("Task Name", ListSortDirection.Ascending));
            }

            // Implement datagrid
            PagedCollectionView myTaskListView = new PagedCollectionView(oMyTaskList);
            this.datagridMyTask.ItemsSource = myTaskListView;
            if (myTaskListView.CanGroup == true)
            {
                // Group tasks by Phase Name
                myTaskListView.GroupDescriptions.Add(new PropertyGroupDescription("PhaseName"));
                // Then group by Complete status.
                myTaskListView.GroupDescriptions.Add(new PropertyGroupDescription("Complete"));
            }
            if (myTaskListView.CanSort == true)
            {
                // By default, sort by Task Name.
                myTaskListView.SortDescriptions.Add(new SortDescription("Task Name", ListSortDirection.Ascending));
            }
        }


        //GET PROJECT TASK LIST - COMBINATION OF 4 FUNCTIONs ABOVE
        protected void GetProjectTaskList()
        {
            //get milestone, put it it msl
            //GetProjectMileStone();

            ////get phase, put it in pl
            //GetProjectPhase(msl);
            ////get task list, put it in taskList
            //GetTaskList(pl);

            ////add data to task datagrid
            //AddData(taskList);
        }



        private void chkboxFilterComplete_Checked(object sender, RoutedEventArgs e)
        {
            PagedCollectionView pcv = this.datagridTaskList_TeamLead.ItemsSource as PagedCollectionView;
            if (pcv != null && pcv.CanFilter == true)
            {
                // Apply the filter.
                pcv.Filter = new Predicate<object>(FilterCompletedTasks);
            }

        }

        private void chkboxFilterComplete_Unchecked(object sender, RoutedEventArgs e)
        {
            PagedCollectionView pcv = this.datagridTaskList_TeamLead.ItemsSource as PagedCollectionView;
            if (pcv != null)
            {
                // Remove the filter.
                pcv.Filter = null;
            }
        }

        public bool FilterCompletedTasks(object t)
        {
            Task task = t as Task;
            return (task.Complete == false);
        }

        private void buttExpand_Click(object sender, RoutedEventArgs e)
        {
            PagedCollectionView pcv = datagridTaskList_TeamLead.ItemsSource as PagedCollectionView;
            try
            {
                foreach (CollectionViewGroup group in pcv.Groups)
                {
                    datagridTaskList_TeamLead.ExpandRowGroup(group, true);
                }
            }
            catch (Exception ex)
            {
                // Could not expand group.
                MessageBox.Show(ex.Message);
            }

        }

        private void buttCollapse_Click(object sender, RoutedEventArgs e)
        {
            PagedCollectionView pcv = datagridTaskList_TeamLead.ItemsSource as PagedCollectionView;
            try
            {
                foreach (CollectionViewGroup group in pcv.Groups)
                {
                    datagridTaskList_TeamLead.ScrollIntoView(group, null);
                    datagridTaskList_TeamLead.CollapseRowGroup(group, true);
                }
            }
            catch (Exception ex)
            {
                // Could not collapse group.
                MessageBox.Show(ex.Message);
            }

        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void buttProfile_Click(object sender, RoutedEventArgs e)
        {
            Profile p = new Profile(curUser);
            p.Closed += new EventHandler(pClose);
            p.Show();
        }
        void pClose(object sender, EventArgs e)
        {
            Profile p = (Profile)sender;
            if (p.DialogResult == true)
            {
                user newUser = new user();

                newUser.user_email = curUser.user_email;
                newUser.user_address = p.txtboxAddress.Text;
                newUser.user_birthday = p.datepickBirthday.SelectedDate;
                newUser.user_firstname = p.txtboxFirstName.Text;
                newUser.user_lastname = p.txtboxLastName.Text;
                if (p.passboxOldPassword.Password != "")
                    newUser.user_password = p.passboxNewPassword.Password;
                else
                    newUser.user_password = curUser.user_password;
                newUser.user_phone = p.txtboxPhoneNumber.Text;
                newUser.user_sex = Convert.ToInt32(p.comboSex.SelectedIndex) - 1;

                //update using webservice
                pmWebServiceClient ws = new pmWebServiceClient();
                ws.UpdateUserDetailsCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(ws_UpdateUserDetailsCompleted);
                ws.UpdateUserDetailsAsync(Convert.ToInt32(curUser.user_id), newUser);
            }
        }

        void ws_UpdateUserDetailsCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            MessageBox.Show("User is updated successfully!");
        }

        //NEW TASK-BEGIN
        private void buttNewTask_Click(object sender, RoutedEventArgs e)
        {
            CreateTask ct = new CreateTask(pl, ml);
            ct.Closed += new EventHandler(ctClose);
            ct.Show();
        }
        void ctClose(object sender, EventArgs e)
        {
            CreateTask ct = (CreateTask)sender;
            if (ct.DialogResult == true)
            {
                //task nt = new task();

                //nt.phase_id = Convert.ToInt32(((Phase)ct.autoboxPhase.SelectedItem).ID);
                //nt.task_name = ct.txtboxTaskName.Text;
                //nt.task_start_date = Convert.ToDateTime(ct.datepickStartDate.SelectedDate);
                //nt.task_end_date = Convert.ToDateTime(ct.datepickDeadLine.SelectedDate);
                pmWebServiceClient ws = new pmWebServiceClient();
                ws.InsertTaskCompleted += new EventHandler<AsyncCompletedEventArgs>(ws_InsertTaskCompleted);
                ws.InsertTaskAsync(Convert.ToInt32(((Phase)ct.autoboxPhase.SelectedItem).ID) , ct.txtboxTaskName.Text , "description" ,  Convert.ToDateTime(ct.datepickStartDate.SelectedDate) , Convert.ToDateTime(ct.datepickDeadLine.SelectedDate) , "report" , "status");
            }
        }

        void ws_InsertTaskCompleted(object sender, AsyncCompletedEventArgs e)
        {
            MessageBox.Show("Task is created successfully!");
        }
        //NEW TASK-END

        //EDIT TASK
        private void buttEditTask_Click(object sender, RoutedEventArgs e)
        {
            EditTask et = new EditTask(pl, ml);
            et.Closed += new EventHandler(etClose);
            et.Show();
        }
        void etClose(object sender, EventArgs e)
        {
            EditTask et = (EditTask)sender;
        }

        private void buttLogout_Click(object sender, RoutedEventArgs e)
        {
            PageSwitch ps = this.Parent as PageSwitch;
            ps.Navigate(new MainPage());
        }

        private void buttUserControlPanel_Click(object sender, RoutedEventArgs e)
        {
            PageSwitch ps = this.Parent as PageSwitch;
            ps.Navigate(new UserControlPanel());
        }

        private void buttUpdateTaskStatus_Click(object sender, RoutedEventArgs e)
        {
            MyTask k = this.datagridMyTask.SelectedItem as MyTask;
            
            MessageBox.Show(k.TaskID);
        }

        //DELETE TASK
        private void buttDeleteTask_Click(object sender, RoutedEventArgs e)
        {
            if (datagridTaskList_TeamLead.SelectedIndex >= 0)
            {
                Task cf = new Task();
                cf = (Task)datagridTaskList_TeamLead.SelectedItem;

                ConfirmWindow cw = new ConfirmWindow(cf);
                cw.Closed += new EventHandler(cw_Closed);
                cw.Show();
            }
        }

        void cw_Closed(object sender, EventArgs e)
        {
            ConfirmWindow cw = (ConfirmWindow)sender;
            if (cw.DialogResult == true)
            {
                pmWebServiceClient ws = new pmWebServiceClient();
                //ws.Task
            }
        }

        private void buttUpdateTaskStatus_Click_1(object sender, RoutedEventArgs e)
        {

        }

        private void buttRenameFile_Click(object sender, RoutedEventArgs e)
        {

        }

        private void buttDownloadFile_Click1(object sender, RoutedEventArgs e)
        {
            Documentation selectedRow = (Documentation)datagridDocuments1.SelectedItem;
            string url = System.Windows.Application.Current.Host.Source.AbsoluteUri;
            url = url.Substring(0, url.IndexOf("ClientBin")) + selectedRow.Url;
            UriBuilder ub = new UriBuilder(url);
            HtmlPage.Window.Navigate(ub.Uri);
        }

        private void buttDownloadFile_Click2(object sender, RoutedEventArgs e)
        {
            Documentation selectedRow = (Documentation)datagridDocuments2.SelectedItem;
            string url = System.Windows.Application.Current.Host.Source.AbsoluteUri;
            url = url.Substring(0, url.IndexOf("ClientBin")) + selectedRow.Url;
            UriBuilder ub = new UriBuilder(url);
            HtmlPage.Window.Navigate(ub.Uri);
        }

        // UPLOAD
        private string FileName;
        private void buttUploadFile_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UploadManager uploader = new UploadManager();
                FileName = uploader.StartSelectFileAndUpload(projectID);

                anotherWebServiceClient aws = new anotherWebServiceClient();
                aws.InsertFolderCompleted += new EventHandler<AsyncCompletedEventArgs>(ws_InsertFolderCompleted);
                aws.InsertFolderAsync(projectID);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error!", MessageBoxButton.OK);
            }
        }

        void ws_InsertFolderCompleted(object sender, AsyncCompletedEventArgs e)
        {
            anotherWebServiceClient aws = new anotherWebServiceClient();
            aws.InsertDocumentationCompleted += new EventHandler<AsyncCompletedEventArgs>(aws_InsertDocumentationCompleted);
            aws.InsertDocumentationAsync(currentUserForUploadPurpose.user_id, projectID, FileName, "Uploaded/" + projectID.ToString() + "/" + FileName, DateTime.Today, "status");
        }

        void aws_InsertDocumentationCompleted(object sender, AsyncCompletedEventArgs e)
        {
            MessageBox.Show("File uploaded successfully", "Uploaded", MessageBoxButton.OK);
            GetDocumentations();
        }
    }
}
